import api from '@/utils/http/api.js'

//列表上拉加载配置  http://www.mescroll.com/uni.html#begin
const upOption = {
	auto: false,
	textLoading: "加载中...",
	textNoMore: "--没有更多了--",
	page: {
		size: 20,
	},
	empty: {
		use: true,
		icon: "/static/img/empty.png",
		tip: "暂无数据",
		fixed: true,
		top: "120px",
		zIndex: 99
	},
	top: "47px"
}

const downOption = {
	use: false,
	auto: false,
	// textInOffset: "下拉刷新",
	// textOutOffset: "释放更新",
	// isLock: false,
	// offset: "80"
}

const itemIcon = "/static/img/icon.png"; //列表图标
const activeColor = "#467DB9";
const barWidth = '150';

let IsNullOrEmpty = (obj) => {
	if (typeof(obj) !== "undefined") {
		return !(obj != null && obj !== "");
	} else {
		return true;
	}
}

// tree转一维数组
let treeToArray = (nodes) => {
	var r = [];
	if (Array.isArray(nodes)) {
		for (var i = 0, l = nodes.length; i < l; i++) {
			r.push(nodes[i]); // 取每项数据放入一个新数组
			if (Array.isArray(nodes[i]["children"]) && nodes[i]["children"].length > 0)
				// 若存在children则递归调用，把数据拼接到新数组中，并且删除该children
				r = r.concat(treeToArray(nodes[i]["children"]));
			delete nodes[i]["children"]
		}
	}
	return r;
}

// 对象或数组深拷贝
let deepClone = (source) => {
	const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
	for (let keys in source) { // 遍历目标
		if (source.hasOwnProperty(keys)) {
			if (source[keys] && typeof source[keys] === 'object') { // 如果值是对象，就递归一下
				targetObj[keys] = source[keys].constructor === Array ? [] : {};
				targetObj[keys] = deepClone(source[keys]);
			} else { // 如果不是，就直接赋值
				targetObj[keys] = source[keys];
			}
		}
	}
	return targetObj;
}

// 给树形(层级)数组添加层级标识
const arrayTreeSetLevel = (array, levelName = '_level', childrenName = 'children', dwdm = '') => {
	if (!Array.isArray(array)) return []
	const recursive = (array, level = 0) => {
		level++
		return array.map(v => {
			v[levelName] = level

			if (level == 2) {
				dwdm = v.PID
			}

			if (level == 3) {
				v["dwdm"] = dwdm
			}

			const child = v[childrenName]
			if (child && child.length) recursive(child, level)
			return v
		})
	}
	return recursive(array)
}

// 给树形(层级)数组添加层级标识
const SetLevelForDispatch = (array, levelName = '_level', childrenName = 'children', dwdm = '') => {
	if (!Array.isArray(array)) return []
	const recursive = (array, level = -1) => {
		level++
		return array.map(v => {
			v[levelName] = level
			const child = v[childrenName]
			if (child && child.length) recursive(child, level)
			return v
		})
	}
	return recursive(array)
}

//去重 arr:数据源、ItemName：去重条件
let deWeightArray = (arr, ItemName) => {
	let map = new Map();
	for (let item of arr) {
		if (!map.has(item[ItemName])) {
			map.set(item[ItemName], item);
		}
	}
	return [...map.values()];
}

//Storage跳转传参写入
let setStorage = (pageData, url = '', key = 'pageData') => {
	uni.setStorage({
		key: key,
		data: pageData,
		success: (e) => {
			uni.navigateTo({
				url: url
			})
		}
	})
}

//Storage跳转传参读取
let getStorage = (titleName = 'title', key = 'pageData') => {
	const data = uni.getStorageSync(key);
	uni.setNavigationBarTitle({
		title: data[titleName]
	})
	return data;
}

// 不含icon提示框
const toast = (title) => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: title,
			icon: "none",
			duration: 2000,
			success: () => {
				setTimeout(() => {
					resolve
				}, 2000)
			}
		})
	})
};

// 成功提示框
const toastSuccess = (title) => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: title,
			image: '/static/img/icon/success2.png',
			duration: 2000,
			success: () => {
				setTimeout(() => {
					resolve()
				}, 2000)
			}
		})
	})
};

// 错误提示框
const toastFail = (title) => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: title,
			image: '/static/img/icon/fail.png',
			duration: 2000,
			success: () => {
				setTimeout(() => {
					resolve()
				}, 2000)
			}
		})
	})
};

// 警告提示框
const toastWarning = (title) => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: title,
			mask: true,
			image: '/static/img/icon/warning.png',
			duration: 2000,
			success: () => {
				setTimeout(() => {
					resolve()
				}, 2000)
			}
		})
	})
};

// 提示loading
const toastShow = (title) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: title,
			mask: true,
			success: () => {
				resolve()
			}
		})
	})
};

// 隐藏loading
const toastHide = () => {
	return new Promise((resolve, reject) => {
		uni.hideLoading({
			success: () => {
				resolve()
			}
		})
	})
};

const uEncode = (param) => {
	return encodeURIComponent(JSON.stringify(param))
}

const uDecode = (param) => {
	if (typeof param != "undefined") {
		return JSON.parse(decodeURIComponent(param))
	}
}

//计算组件的高度
const getEleHeight = (_this, uid) => {
	let height;
	const query = uni.createSelectorQuery().in(_this);
	query.select(uid).boundingClientRect(res => {
		height = res.height;
	}).exec();
	return height;
}

const getColumn = (_this) => {

	return _this.$api.myAjaxFunc(Config.PlatformAPI + publicJs.Config.ListData.GetColumn, {
		key: _this.listCode
	}).then((res) => {

		const list = res.columns.filter(item => !_this.$gl.IsNullOrEmpty(item.header));

		_this.columnList = list.map(item => {
			return {
				key: item.field,
				text: item.header,
			}
		})

		return res.url;
	})

}

//上拉加载更多，不分页数据直接加载
const loadMore = (_this, index, size, obj) => {

	let pageIndex = index - 1;

	let jsonObj = {
		...{
			pageIndex: pageIndex,
			pageSize: size,
			key: _this.listCode,
			filter: JSON.stringify(_this.filter),
		},
		...obj
	}

	_this.$api.myAjaxFunc(_this.api, jsonObj).then((res) => {
		const data = res.data ?? res;
		const total = res.total ?? res.length;
		_this.mescroll.endBySize(data.length, total);
		_this.list = [..._this.list, ...data];
	})

}

const assembleData = (modelObj, dataObj, Json = {}) => {

	const list = {};

	const listKey = Object.keys(modelObj);

	listKey.forEach(item => {
		if (!IsNullOrEmpty(dataObj[item])) {
			list[item] = dataObj[item]
		}
	})

	const obj = {
		...modelObj,
		...list
	}

	if (IsNullOrEmpty(obj.BDBM)) {
		obj.BDBM = dataObj.Business_Key;
	}

	obj.showFlowButton = true;
	obj.showFlowOpinion = true;
	obj.Json = JSON.stringify(Json);

	return obj;
}

export default {
	assembleData,
	toast,
	toastSuccess,
	toastFail,
	toastWarning,
	toastShow,
	toastHide,
	barWidth,
	activeColor,
	itemIcon,
	deepClone,
	treeToArray,
	arrayTreeSetLevel,
	SetLevelForDispatch,
	deWeightArray,
	uEncode,
	uDecode,
	getEleHeight,
	getStorage,
	setStorage,
	IsNullOrEmpty,
	getColumn,
	upOption,
	downOption,
	loadMore
}
